<template>
	<view
		class="card-box"
		v-if="
			deviceStore.deviceStatus?.status !== 1 &&
			deviceStore.deviceStatus?.conn_status === 1
		">
		<view class="top">
			<view class="top-left">
				<up-text
					:text="displayTips"
					color="#4E6FFF"
					size="12"></up-text>
			</view>
			<view class="top-right">
				<up-avatar
					shape="square"
					size="30"
					:src="
						'/static/image/device/' +
						deviceStore.deviceStatus?.rubber +
						'_active.png'
					"></up-avatar>
				<up-text
					:text="getDamBoard(deviceStore.deviceStatus?.rubber)"
					color="#333"
					size="12"></up-text>
				<up-avatar
					shape="square"
					size="30"
					class="center-pic"
					:src="
						'/static/image/device/position_' +
						getLocation(deviceStore.deviceStatus?.location_status) +
						'.png'
					"></up-avatar>
				<view class="color-pic">
					<up-avatar
						shape="square"
						size="11"
						:src="
							'/static/image/device/circle' +
							getCirclePic() +
							'.png'
						"></up-avatar>
				</view>
				<up-text
					:text="`${
						deviceStore.deviceStatus?.garbage_inventory
							? deviceStore.deviceStatus?.garbage_inventory
							: 0
					}%`"
					color="rgba(0, 0, 0, 0.9)"
					size="12"></up-text>
			</view>
		</view>
		<up-row class="top-bottom" justify="space-between" gutter="10">
			<up-col span="4" class="col-span">
				<up-text
					:text="t('device.cleaningProgress')"
					color="#999"
					size="12"></up-text>
				<up-row justify="center">
					<up-text
						:text="`${
							deviceStore.deviceStatus?.status === 1
								? 0
								: getProcess
						}`"
						color="#333333"
						size="16"></up-text>
					<up-text text="%" color="#333" size="10"></up-text>
				</up-row>
			</up-col>
			<up-col span="4" class="col-span">
				<up-text
					:text="t('device.time')"
					color="#999"
					size="12"></up-text>
				<up-row justify="center">
					<up-text
						:text="`${
							deviceStore.deviceStatus?.status === 1
								? 0
								: getMin(deviceStore.deviceProgress?.duration)
						}`"
						color="#333333"
						size="16"></up-text>
					<up-text text="min" color="#333" size="10"></up-text>
					<up-text
						:text="`${
							deviceStore.deviceStatus?.status === 1
								? 0
								: getSecond(
										deviceStore.deviceProgress?.duration
								  )
						}`"
						color="#333333"
						size="16"></up-text>
					<up-text text="sec" color="#333" size="10"></up-text>
				</up-row>
			</up-col>
			<up-col span="4" class="col-span">
				<up-text
					:text="t('device.area')"
					color="#999"
					size="12"></up-text>
				<up-row justify="center">
					<up-text
						:text="`${
							deviceStore.deviceStatus?.status === 1
								? 0
								: getSafeNumber(
										deviceStore.deviceProgress?.area
								  )
						}`"
						color="#333333"
						size="16"></up-text>
					<up-text text="m²" color="#333" size="10"></up-text>
				</up-row>
			</up-col>
		</up-row>
	</view>
</template>

<script setup lang="ts">
import { useDeviceStore } from "@/stores/device";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { useDeviceInfo } from "@/utils/getDeviceInfo";
import { onBeforeRouteLeave } from "vue-router";
import { computed, watch, onUnmounted, onMounted, ref } from "vue";
const deviceStore = useDeviceStore();
const { getDeviceTips, clearTime } = useDeviceInfo();
const props = defineProps<{
	device_sn: string;
}>();
watch(
	() => [deviceStore.deviceStatus, deviceStore.deviceProgress],
	() => {},
	{ immediate: true, deep: true }
);
watch(
	() => deviceStore.showGray,
	(val) => {
		if (val) {
			getDeviceTips(props.device_sn);
		} else {
			clearTime(1);
		}
	},
	{ immediate: true, deep: true }
);
// 组件卸载时清理
onUnmounted(() => {
	clearTime();
});

onBeforeRouteLeave((to, from, next) => {
	clearTime();
	next(); // 一定要调用 next()，否则阻止跳转
});
interface RubberType {
	name: string;
	value: string;
}
interface LocationStatus {
	gps: number;
	value: string;
}

type GpsStatus = 0 | 1 | -1;
type ScopeType = number | undefined | null;
// 需要显示提示的状态集合
const SHOW_TIPS_STATUSES = new Set([2, 9, 10, 11]);

// 提示语映射表
const TIPS_MAPPING = {
	正在前往: t("deviceTips.go"),
	正在清扫: t("deviceTips.clean"),
	正在清扫中: t("deviceTips.clean"),
	返回充电桩中: t("deviceTips.back"),
	返回充电中: t("deviceTips.back"),
};

// 计算是否显示提示
const shouldShowTips = computed(() => {
	return SHOW_TIPS_STATUSES.has(deviceStore.deviceStatus?.status);
});

// 国际化提示处理
const getNewTips = (tips: string): string => {
	if (!tips) return "";

	let processedTips = tips;

	// 使用映射表替换
	Object.entries(TIPS_MAPPING).forEach(([zh, translated]) => {
		processedTips = processedTips.replace(zh, translated);
	});

	return processedTips;
};

// 最终显示内容
const displayTips = computed(() => {
	return shouldShowTips.value ? getNewTips(deviceStore.tipsMsg) : "";
});
const getMin = (scope: ScopeType): string => {
	if (typeof scope !== "number" || isNaN(scope)) {
		return "0";
	}
	const min = scope / 60;
	return min.toFixed(0);
};
const getSecond = (scope: ScopeType): number => {
	if (typeof scope !== "number" || isNaN(scope)) {
		return 0;
	}

	return Math.floor(scope % 60);
};
const getSafeNumber = (
	value: number | undefined,
	precision: number = 2
): string => {
	return value?.toFixed(precision) ?? "0";
};
// 定位状态配置（常量提升）
const LOCATION_STATUSES: LocationStatus[] = [
	{ gps: 0, value: "open" },
	{ gps: 1, value: "closed" },
	{ gps: -1, value: "lost" },
];
type RubberSize = "small" | "median" | "big" | "huge" | "auto";
// 获取定位状态
const getLocation = (val: GpsStatus): string | undefined => {
	return LOCATION_STATUSES.find((item) => item.gps === val)?.value;
};
// 橡胶类型配置（常量提升）
const RUBBER_TYPES: RubberType[] = [
	{ name: "small", value: t("device.rubber.small") },
	{ name: "median", value: t("device.rubber.median") },
	{ name: "big", value: t("device.rubber.big") },
	{ name: "huge", value: t("device.rubber.huge") },
	{ name: "auto", value: t("device.rubber.huge") },
];
const getCirclePic = () => {
	const percent = deviceStore.deviceStatus?.garbage_inventory
		? deviceStore.deviceStatus?.garbage_inventory
		: 0;
	if (percent >= 70) {
		return 3;
	} else if (percent >= 40) {
		return 2;
	} else {
		return 1;
	}
};
const circleColor = computed(() => {
	const inventory = deviceStore.deviceStatus?.garbage_inventory
		? deviceStore.deviceStatus?.garbage_inventory
		: 0;

	if (inventory >= 70) {
		return "#E34D59"; // 红色，库存 >= 70%
	} else if (inventory >= 40) {
		return "#ED7B2F"; // 橙色，40% <= 库存 < 70%
	} else {
		return "#52D668"; // 绿色，库存 < 40%
	}
});
// 获取挡板值
const getDamBoard = (val: RubberSize): string | undefined => {
	return RUBBER_TYPES.find((item) => item.name === val)?.value;
};
// 常量定义
const MIN_PROGRESS = 0;
const MAX_PROGRESS = 100;
const MIN_TIME = 1;
const MAX_TIME = 4;

// 计算处理进度
const getProcess = computed((): number => {
	const progress = deviceStore.deviceProgress?.progress
		? deviceStore.deviceProgress?.progress
		: 0;

	// 无效进度处理
	if (!progress || progress <= MIN_PROGRESS) {
		return MIN_PROGRESS;
	}

	// 计算时间因子（限制范围）
	const timeFactor = Math.max(
		MIN_TIME,
		Math.min(MAX_TIME, Math.floor(progress * 4) + 1)
	);

	// 计算最终进度百分比
	const finalProgress = Math.min(MAX_PROGRESS, progress * MAX_PROGRESS);

	return Math.round(finalProgress);
});
const topHeight = ref("56px");
onMounted(() => {
	// 获取状态栏高度
	// #ifdef APP-PLUS
	const statusBarHeight = ref(0);
	const systemInfo = uni.getSystemInfoSync();
	statusBarHeight.value = systemInfo.statusBarHeight || 0;
	topHeight.value = statusBarHeight.value + 56 + "px";
	// #endif
});
</script>

<style lang="scss" scoped>
.card-box {
	display: block;
	position: fixed;
	top: v-bind(topHeight);
	width: calc(100% - 10px);
	background: #fff;
	left: 5px;
	z-index: 2;
	border-radius: 10px;
	box-shadow: 0px 3px 6px 1px rgba(0, 0, 0, 0.16);
	.top {
		display: flex;
		width: 100%;
		padding: 2px 10px 0;
		box-sizing: border-box;
		align-items: center;
		border-bottom: 1px solid #f6f7f8;
	}
	.top-left {
		flex: 50%;
	}
	.top-right {
		display: flex;
		flex: 50%;
		align-items: center;
		justify-content: flex-end;
		:deep(.u-text) {
			width: fit-content !important;
			flex: 0 1 auto !important;
		}
		.center-pic {
			margin: 0 10rpx;
		}
		.color-pic {
			border: 2px solid v-bind(circleColor);
			border-radius: 50%;
			width: 16px;
			height: 16px;
			display: flex;
			justify-content: center;
			align-items: center;
			margin-right: 10rpx;
		}
	}
	.top-bottom {
		padding: 9px 0;
	}
	.col-span {
		display: flex;
		flex-direction: column;
		align-items: center !important;
		justify-content: center;
		border-right: 0.5px solid #e0e0e0;
		:deep(.u-text) {
			width: fit-content !important;
			justify-content: center;
		}
	}
}
</style>
